<?php
/**
 * 标签管理
 * User: ws
 * Date: 2018/8/6
 * Time: 15:46
 */

namespace app\admin\controller;
use app\admin\model\Label as LabelModel;

class Label extends Init
{
    function index(){
        if ($this->request->isAjax()) {
            $list = LabelModel::paginate(100)->toArray();
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }


    function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $model = new LabelModel();
            if(empty($data['label_id'])){
                unset($data['label_id']);
                $rul = $model->add($data);
            }else{
                if(empty($data['image'])){
                    unset($data['image']);
                }else{
                    $labelI = $model->field('image')->where("label_id = {$data['label_id']}")->find();
                    $label_img = $labelI->toArray();
                    unlink('.'.$label_img['image']);
                }

                //$rul = LabelModel::update($data);
                $rul = $model->edit($data);
            }

            if ($rul) {
                return json(array('code'=>200,'msg'=>'添加成功'));
            }
            return json(array('code'=>0,'msg'=>'添加失败'));
        }


        $parent = LabelModel::where('parent_id',0)->paginate(30)->toArray();
        if(!empty(input('id'))){
            $list = LabelModel::where('label_id', input('id'))->find()->toArray();
            return view('add',['list'=>$list,'pare'=>$parent['data']]);
        }
        $list['name'] = '';
        $list['image'] = '';
        $list['label_id'] = '';
        return view('add',['pare'=>$parent['data'],'list'=>$list]);
    }



    public function del(){
        $id = input('param.id');
        $lalel = LabelModel::where('parent_id',$id)->find();
        if($lalel){
            return json(array('code'=>0,'msg'=>'删除失败，请先删除下级标签'));
        }
        if (!LabelModel::destroy(['label_id' => $id])) {
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
        return json(array('code'=>200,'msg'=>'删除成功'));
    }
}